package http_config

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

const (
	LiveDbUsername = "root"
	LiveDbPassword = "123456"
)

var CONF *Config = nil

type Config struct {
	LogLevel       string `json:"log_level"`         // 日志级别
	DbHost         string `json:"db_host"`           // 数据库地址
	HttpPort       int32  `json:"http_port"`         // http服务端口
	TapSdkClientId string `json:"tap_sdk_client_id"` // taptap sdk
	TapSdkSkip     bool   `json:"tap_sdk_skip"`      // 是否跳过taptap sdk验证
	LogSql         bool   `json:"log_sql"`           // 是否记录sql日志
	DevEnv         bool   `json:"dev_env"`           // 是否为开发环境

	BiliGameId     int32  `json:"bili_game_id"`
	BiliMerchantId int32  `json:"bili_merchant_id"`
	BiliSecret     string `json:"bili_secret"` // b站秘钥
	Key4399        string `json:"key_4399"`
	KeyHYKB        string `json:"key_hykb"`
	RegisterMax    int64  `json:"register_max"`
}

func (c *Config) GetDbHost() string {
	return LiveDbUsername + ":" + LiveDbPassword + c.DbHost
}

func InitConfig() {
	if len(os.Args) > 1 && os.Args[1] == "config" {
		c := &Config{
			LogLevel:       "debug",
			DbHost:         "@tcp(192.168.3.247:3306)/jgame?charset=utf8mb4&parseTime=true&loc=Local&timeout=10s",
			HttpPort:       8888,
			TapSdkClientId: "hireyfueelfcwww377",
			TapSdkSkip:     true,
			LogSql:         false,
			DevEnv:         true,
			BiliGameId:     0,
			BiliMerchantId: 0,
			BiliSecret:     "",
			Key4399:        "",
		}
		data, err := json.MarshalIndent(c, "", "\t")
		if err != nil {
			panic(err)
		}
		str := string(data)
		str = strings.ReplaceAll(str, "\\u003c", "<")
		str = strings.ReplaceAll(str, "\\u003e", ">")
		str = strings.ReplaceAll(str, "\\u0026", "&")
		err = os.WriteFile("./config.json", []byte(str), 0644)
		if err != nil {
			panic(err)
		}
		os.Exit(0)
	}

	filePath := "./config.json"
	if len(os.Args) > 1 {
		filePath = os.Args[1]
	}
	CONF = new(Config)
	CONF.loadConfigFile(filePath)
}

func GetConfig() *Config {
	return CONF
}

func (c *Config) loadConfigFile(filePath string) {
	data, err := os.ReadFile(filePath)
	if err != nil {
		info := fmt.Sprintf("config file load error: %v\n", err)
		panic(info)
	}
	err = json.Unmarshal(data, c)
	if err != nil {
		info := fmt.Sprintf("config file parse error: %v\n", err)
		panic(info)
	}
}
